package net.borlis.server.filesystem.api;

import javax.speech.AudioException;
import javax.speech.Central;
import javax.speech.EngineException;
import javax.speech.synthesis.Synthesizer;
import javax.speech.synthesis.SynthesizerModeDesc;
import java.beans.PropertyVetoException;
import java.util.Locale;

/**
 * Created by borlis on 26.12.2014.
 */
public class SpeakSynthezer {

    private Synthesizer synthesizer;
    private SpeakerMode speakerMode;

    private static final String DEFAULT_MAIL_VOICE = "kevin16";
    private static final Locale DEFAULT_SPEAK_LOCALE = Locale.US;

    public SpeakSynthezer(String voiceName, Locale locale) {
        this.speakerMode = new SpeakerMode(locale == null ? DEFAULT_SPEAK_LOCALE : locale);
        try {
            System.setProperty("freetts.voices",
                    "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory");
            Central.registerEngineCentral("com.sun.speech.freetts.jsapi.FreeTTSEngineCentral");
            synthesizer = Central.createSynthesizer(speakerMode.getDesc());
            synthesizer.allocate();
            synthesizer.resume();
            speakerMode.setDesc((SynthesizerModeDesc) synthesizer.getEngineModeDesc());
            synthesizer.getSynthesizerProperties().setVoice(
                    new Voize(voiceName == null ? DEFAULT_MAIL_VOICE : voiceName, speakerMode.getDesc()).getVoice());
        } catch (EngineException e) {
            e.printStackTrace();
        } catch (AudioException e) {
            e.printStackTrace();
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }

    public void setSynthesizer(Synthesizer synthesizer) {
        this.synthesizer = synthesizer;
    }

    public Synthesizer getSpeaker() {
        return this.synthesizer;
    }
}
